<template>
  <custom-dialog
    ref="dialog" title="驾车路线规划" class="no-padding-body"
    width="60%"
    :show-cancel-button="true" :show-confirm-button="false"
  >
    <div style="width:100%;height:500px;">
      <el-amap
        ref="amap"
        :option="{
          mapStyle: 'amap://styles/macaron',
          zoom: 14,
          center: to
        }"
        @map-init="onMapInit"
      ></el-amap>
    </div>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import Vue from 'vue'
import VueAMap from '@/plugins/amap'

Vue.use(VueAMap)
export default {
  name: 'index',
  components: { CustomDialog },
  props: {
    to: {
      type: Array,
      required: true,
      validator (value) {
        return Array.isArray(value) && value.length === 2
      }
    }
  },
  data () {
    return {
      map: null,
    }
  },
  methods: {
    onMapInit (AMap, map) {
      this.map = map
      let start = new AMap.LngLat(115.892151, 28.676493)
      const end = new AMap.LngLat(...this.to)
      setTimeout(() => {
        this.getLocation((result) => {
          start = result.position
          this.drive(map, start, end)
        }, () => {
          this.$message.error('定位失败')
          this.drive(map, start, end)
        })
      }, 20)
    },
    open () {
      this.$refs.dialog.open()
    },
    drive (map, startLngLat, endLngLat) {
      const vm = this
      const AMap = window.AMap
      AMap.plugin('AMap.Driving', function () {
        const driving = new AMap.Driving({
          map,
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          policy: AMap.DrivingPolicy.LEAST_TIME
        })

        console.log('startLngLat: ', startLngLat)
        console.log('endLngLat: ', endLngLat)

        driving.search(startLngLat, endLngLat, function (status, result) {
          if (status === 'complete') {
            console.log('驾车路线规划成功')
          } else {
            vm.$message.error('驾车路线规划失败')
          }
        })
      })
    },
    getLocation (onComplete, onError) {
      const AMap = window.AMap
      const map = this.map
      AMap.plugin('AMap.Geolocation', function () {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：5s
          buttonPosition: 'RB', // 定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
        })
        map.addControl(geolocation)
        geolocation.getCurrentPosition(function (status, result) {
          // eslint-disable-next-line
          if (status == 'complete') {
            onComplete(result)
          } else {
            onError(result)
          }
        })
      })
    },
  },
}
</script>

<style scoped>
.no-padding-body >>> .el-dialog__body {
  padding: 0;
}
</style>
